import { CallbackType, waitLastEventLoop, waitMiddleEventLoop } from '../utils';
// 这里只考虑简化情况，保证promiseFunc最终一定是resolved，不可能是rejected
const promiseCount = (promiseFunc: (...args: ReadonlyArray<any>) => Promise<unknown>, count: number) => new Promise<void>(async resolve => {
  for (let i = 0; i < count; i++) {
    await promiseFunc();
  }
  resolve();
});

export const waitCountEventLoop = async (callback: CallbackType = () => { }, count = 1) => {
  await promiseCount(waitMiddleEventLoop, count);
  waitLastEventLoop(callback);
};
export const waitCountEmptyEventLoop = async (count = 1) => waitCountEventLoop(async () => { }, count);
// const s = performance.now();
// promiseCount(() => waitMiddleEventLoop(), 100).then(() => {
//   console.log(performance.now() - s);
// });

// // 例如
// (async () => {
//   await promiseCount(() => new Promise(resolve => setTimeout(resolve, 1e3)), 2);
//   console.log('finish');
// });
// //等价于
// (async () => {
//   await new Promise(resolve => setTimeout(resolve, 1e3));
//   await new Promise(resolve => setTimeout(resolve, 1e3)); // 重复2次
//   console.log('finish');
// });